extends CharacterBody2D

# 配置参数
@export var swim_speed: float = 50.0          # 基础游动速度
@export var turn_speed: float = 2.0           # 转向速度（弧度/秒）
@export var wander_radius: float = 100.0      # 随机目标点生成半径
@export var target_update_interval: float = 3.0  # 目标点更新间隔

# 鱼缸边界（通过编辑器设置）
@export var tank_rect: Rect2 = Rect2(0, 0, 800, 600)

# 运行时变量
var _current_speed: float = 0.0
var _target_position: Vector2
var _current_angle: float = 0.0
var _wander_timer: float = 0.0

func _ready():
	# 初始随机目标点
	_update_target_position()
	_current_angle = rotation

func _physics_process(delta):
	_wander_timer += delta
	
	# 定期更新目标点
	if _wander_timer >= target_update_interval:
		_update_target_position()
		_wander_timer = 0.0
	
	# 计算移动方向
	var to_target = _target_position - global_position
	var target_angle = to_target.angle()
	
	# 平滑转向
	_current_angle = lerp_angle(
		_current_angle, 
		target_angle, 
		turn_speed * delta
	)
	
	# 速度控制（靠近目标时减速）
	var distance_factor = clamp(to_target.length() / wander_radius, 0.2, 1.0)
	_current_speed = lerp(_current_speed, swim_speed * distance_factor, 5 * delta)
	
	# 应用运动
	velocity = Vector2(_current_speed, 0).rotated(_current_angle)
	rotation = _current_angle
	
	move_and_slide()

# 生成新的有效目标点
func _update_target_position():
	var new_target = global_position + Vector2(
		randf_range(-wander_radius, wander_radius),
		randf_range(-wander_radius, wander_radius)
	)
	
	# 限制在鱼缸边界内
	_target_position = Vector2(
		clamp(new_target.x, tank_rect.position.x, tank_rect.end.x),
		clamp(new_target.y, tank_rect.position.y, tank_rect.end.y)
	)

# 可视化调试（可选）
func _draw():
	if Engine.is_editor_hint():
		return
		
	# 绘制目标点标记
	draw_circle(_target_position - global_position, 5, Color.RED)
	# 绘制移动方向线
	draw_line(Vector2.ZERO, Vector2(50, 0).rotated(_current_angle), Color.GREEN, 2)
